#include <tasks_manager/task_manager_node.h>

/*******************************************
 * 任务路径/图片记录
 *******************************************/

// 任务组开始/结束记录
Status TaskManagerNode::TaskGroupRecord(TaskGroup& task_group, bool is_start, vector<TaskRecord>& task_records){
    cout << "[TaskGroupRecord] group_id: " << task_group.group_id << endl; 
    Status status;
    v3_msgs::TaskReportManager client_data;
    try{
        // 特殊任务不做处理
        string group_name = task_group.group_name;
        if(group_name == "charging" || group_name == "p2p_move"){
            LogPub("WARN", "[TaskGroupRecord] jump group_name=" + group_name);
            return status;
        }
        // 调用服务
        ros::Time start_time = ros::Time::now();
        client_data.request.option = is_start ? client_data.request.TASK_GROUP_START
            : client_data.request.TASK_GROUP_END;
        client_data.request.task_group = __msg_convert.TaskGroup2V3Msgs(task_group);
        client_data.request.curr_task_id = "";
        if(!__report_record_client.call(client_data)){
            throw(string("report_record_client call failed!"));
        }
        float time_interval = (ros::Time::now() - start_time).toSec();
        ROS_INFO("[TaskGroupRecord] Service <%s> call time cost is %0.3f s. task_records size: %d", 
            __report_record_client.getService().c_str(), time_interval,
            client_data.response.task_records.size());
        // 解析返回数据
        if(!client_data.response.response.success){
            throw(client_data.response.response.message);
        }
        for(auto& task_record : client_data.response.task_records){
            task_records.emplace_back(__msg_convert.V3Msgs2TaskRecord(task_record));
        }
        cout << "[TaskGroupRecord] task_records size: " << task_records.size() << endl; 
    }catch(string& error){
        status.success = false;
        status.message = error;
        LogPub("ERROR", "[TaskGroupRecord] error=" + error);
    }  
    return status;
}


// 单个任务开始/结束记录
Status TaskManagerNode::TaskSingleRecord(TaskGroup& task_group, bool is_start, string curr_task_id, vector<TaskRecord>& task_records){
    cout << "[TaskSingleRecord] group_id: " << task_group.group_id 
        << ", curr_task_id: " << curr_task_id 
        << endl; 
    Status status;
    v3_msgs::TaskReportManager client_data;
    try{
        // 特殊任务不做处理
        for(auto& task_single : task_group.task_list){
            if(task_single.task_base.task_id == curr_task_id){
                string task_name = task_single.task_base.task_name;
                if(task_name == "charging" || task_name == "p2p_move" || task_name == "trans_floor"){
                    LogPub("WARN", "[TaskSingleRecord] jump task_name=" + task_name);
                    return status;
                }
            }
        }
        // 调用服务
        ros::Time start_time = ros::Time::now();
        client_data.request.option = is_start ? client_data.request.TASK_SINGLE_START
            : client_data.request.TASK_SINGLE_END;
        client_data.request.task_group = __msg_convert.TaskGroup2V3Msgs(task_group);
        client_data.request.curr_task_id = curr_task_id;
        if(!__report_record_client.call(client_data)){
            throw(string("report_record_client call failed!"));
        }
        float time_interval = (ros::Time::now() - start_time).toSec();
        ROS_INFO("[TaskSingleRecord] Service <%s> call time cost is %0.3f s.", __report_record_client.getService().c_str(), time_interval);
        // 解析返回数据
        if(!client_data.response.response.success){
            throw(client_data.response.response.message);
        }
        for(auto& task_record : client_data.response.task_records){
            task_records.emplace_back(__msg_convert.V3Msgs2TaskRecord(task_record));
        }
    }catch(string& error){
        status.success = false;
        status.message = error;
    }  
    return status;
}


/*******************************************
 * 清洁报告查询
 *******************************************/

// 清洁报告查询服务函数
bool TaskManagerNode::TaskGroupReportServer(v3_msgs::TaskReportManagerRequest &req, v3_msgs::TaskReportManagerResponse &res){
    ROS_INFO("TaskGroupReportServer option: %d", req.option);
    Status status;
    TaskGroup task_group = __msg_convert.V3Msgs2TaskGroup(req.task_group);
    vector<TaskRecord> task_records;
    switch(req.option){
        case req.QUERY_TASK_RECORD:     //查询指定组合任务记录
            status = TaskGroupReportQuery(task_group.group_id, task_records);
            break;
        case req.QUERY_TASK_RECORD_BYTIME:  //查询组合任务记录（基于时间范围和页数）
            status = TaskGroupReportQuery(req.start_time, req.end_time, req.page, req.page_size, req.is_all_info, task_records);
            break;
        default:
            break;
    }
    cout << "[TaskGroupReportServer] task_records size: " << task_records.size() << endl;
    for(auto task_record : task_records){
        // 充电任务和P2P任务暂不显示
        if(task_record.task_group.group_name == "p2p_move" 
            || task_record.task_group.group_name == "charging") continue;
        res.task_records.emplace_back(__msg_convert.TaskRecord2V3Msgs(task_record));
    }
    res.response.success = status.success;
    res.response.message = status.message;
    return true;
}


// 查询指定组合任务记录，需要group_id
Status TaskManagerNode::TaskGroupReportQuery(string group_id, vector<TaskRecord>& task_records){
    Status status;
    try{
        if(group_id.empty()){
            throw(string("group_id is empty!"));
        }
        __task_db_ptr->QueryTaskRecords(group_id, task_records);
    }catch(string& error){
        status.success = false;
        status.message = error;
    }  
    return status;
}


// 查询组合任务记录（基于时间范围和页数）
Status TaskManagerNode::TaskGroupReportQuery(ros::Time start_time, ros::Time end_time, int page, int page_size,
    bool is_all_info, vector<TaskRecord>& task_records){
    Status status;
    try{
        if(start_time.isZero() || end_time.isZero()){
            throw(string("start_time or end_time is zero!"));
        }
        if(page < 0 || page_size <= 0){
            throw(string("page or page_size is invalid!"));
        }
        string start_time_str =  __msg_convert.TimestampFormat(start_time.sec);
        string end_time_str =  __msg_convert.TimestampFormat(end_time.sec);
        if(!is_all_info){   //只需要简要信息，不包含单个任务内所有信息
            for(auto &task_record : task_records){
                task_record.task_group.task_list.clear();
            }
        }
        __task_db_ptr->FindTaskRecordFromTimeArray(start_time_str, end_time_str, page, page_size, task_records);
    }catch(string& error){
        status.success = false;
        status.message = error;
    }  
    return status;
}
